from django import forms
from web.forms.bootstrap import BootStrap

from web import models
from django.core.exceptions import ValidationError


class ProjectModelForm(BootStrap, forms.ModelForm):
    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        name = self.cleaned_data['name']
        # 1.校验项目是否存在 ()
        exists = models.Project.objects.filter(name=name, creator=self.request.user_obj).exists()
        if exists:
            raise ValidationError('项目名已存在')
        # 2. 校验当前用户的价格策略是否可以在继续添加项目
        count = models.Project.objects.filter(creator=self.request.user_obj).count()
        if count >= self.request.price_policy.project_num:
            raise ValidationError('项目数已超，请购买套餐')
        return name
